//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
// 			VisualNovelToolkit		     /_/_/_/_/_/.
// Copyright ©2013 - Sol-tribe.	/_/_/_/_/_/_/_/_/_/.
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.

using UnityEngine;
using System.Collections;

namespace ViNoToolkit{

	/// <summary>
	/// ColorPanel base class.
	/// </summary>
	public class PanelBase : UIBase {

		public Color m_ActiveColor = Color.white;
		public Color m_DeactiveColor = Color.gray;
		
		[ Range( 0f , 1f ) ]	
		public float alpha = 1f;
				
		public bool m_SetActiveRGB;
		public bool m_SetDeactiveRGB;
		
		public MeshRenderer[] meshRendererCollection;
		
		[ HideInInspector ] public float duration = 1f;
		[ HideInInspector ] public bool m_ChangeColOnTextSet;	
		[ HideInInspector ] public float fadeTo = 1f;
		[ HideInInspector ] public float fadeFrom = 0f;
		[ HideInInspector ] public float fadeDir = 1f;
		
		protected Color m_CurrColor = new Color( 1f , 1f , 1f , 1f );
		protected bool playing;
		
		public void StartFade( float fadeTo , float fadeFrom  ){
			this.fadeTo = fadeTo;
			this.fadeFrom = fadeFrom;
			playing = true;
			
			alpha = fadeFrom;
			
			fadeDir = ( fadeTo > fadeFrom )? 1f : -1f;
		}

		public void UpdateColor( ){
			if( meshRendererCollection != null ){
				if( m_SetActiveRGB ){
					SetActiveColor();
				}
				
				if( m_SetDeactiveRGB ){
					SetDeactiveColor();
				}
				
				m_CurrColor.a = alpha;
				
				for( int i=0;i<meshRendererCollection.Length;i++){
					if( meshRendererCollection[ i ] == null ){
						continue;	
					}
					
					meshRendererCollection[ i ].sharedMaterial.color = m_CurrColor;
					if( alpha < 0.0001f ){
						meshRendererCollection[ i ].enabled = false;
					}
					else{
						meshRendererCollection[ i ].enabled = true;
					}
				}
			}		
		}

		void OnTextSet( string theText ){
			if(m_ChangeColOnTextSet ){
				if( name.Equals( theText ) ){
					SetActiveColor();	
				}
				else{
					SetDeactiveColor();
				}
			}
		}
				
		public void GetChildrenMeshRenderers(){
			if( meshRendererCollection == null ){
				meshRendererCollection = GetComponentsInChildren<MeshRenderer>();		
			}
		}
					
		public override void SetActiveColor(){
			m_SetActiveRGB = true;
			m_SetDeactiveRGB = false;

			m_CurrColor = m_ActiveColor;
			m_CurrColor.a = alpha;
		}
		
		public override void SetDeactiveColor(){
			m_SetActiveRGB = false;
			m_SetDeactiveRGB = true;

			m_CurrColor = m_DeactiveColor;
			m_CurrColor.a = alpha;		
		}
		
		// Update is called once per frame
		public override void OnUpdate () {				
			if( playing ){
				if( duration <= 0f ){
					alpha = fadeTo;
				}
				else{
					alpha += fadeDir * Time.deltaTime / duration;
				}
				if( fadeDir > 0f ){
					if( alpha  >= fadeTo ){
						alpha = fadeTo;
						playing = false;
					}
				}
				else{
					if( alpha  <= fadeTo ){
						alpha = fadeTo;	
						playing = false;
					}				
				}
			}
			
			UpdateColor();
		}
	}

}